package top.fullj.remoting.consumer;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.fullj.remoting.FutureValue;
import top.fullj.remoting.message.Message;

/**
 * @author bruce.wu
 * @since 2022/2/15 10:06
 */
@ChannelHandler.Sharable
public class ClientHandler extends ChannelDuplexHandler {

    private static final Logger LOG = LoggerFactory.getLogger(ClientHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        LOG.info("connection open: local={}, remote={}",
                ctx.channel().localAddress(), ctx.channel().remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        LOG.info("connection lost: local={}, remote={}",
                ctx.channel().localAddress(), ctx.channel().remoteAddress());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Message reply = (Message) msg;
        AttributeKey<FutureValue<Message>> msgId = AttributeKey.valueOf(reply.getId());
        FutureValue<Message> future = ctx.channel().attr(msgId).get();
        if (future != null) {
            future.setValue(reply);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        LOG.error("connection error!", cause);
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        //TODO prepare
        super.write(ctx, msg, promise);
    }

}
